#!/usr/bin/env bash

# Special handling for single-argument commands
if [ $# -eq 1 ]; then
    if [ "$1" = "d" ]; then
        # d subcommand handler
        # Generate timestamp
        TIMESTAMP=$(date +"%Y-%m-%d--%H-%M")

        # Define target filename
        TARGET_FILE="dialog-$TIMESTAMP.md"

        # Create empty file
        if ! touch "$TARGET_FILE"; then
            echo "Error: Failed to create '$TARGET_FILE'."
            exit 1
        fi

        # Success message
        echo "Success: Created empty file '$TARGET_FILE'."
        exit 0
    elif [ "$1" = "bo" ]; then
        # bo subcommand handler (bubble only)
        # Check if bubble only template exists
        if [ ! -f "icm-bubble-only-template.md" ]; then
            echo "Error: File 'icm-bubble-only-template.md' does not exist."
            exit 1
        fi

        # Generate timestamp
        TIMESTAMP=$(date +"%Y-%m-%d--%H-%M")

        # Define target filename
        TARGET_FILE="icm-bubble-only-$TIMESTAMP.md"

        # Copy template file
        if ! cp "icm-bubble-only-template.md" "$TARGET_FILE"; then
            echo "Error: Failed to copy 'icm-bubble-only-template.md' to '$TARGET_FILE'."
            exit 1
        fi

        # Success message
        echo "Success: Copied 'icm-bubble-only-template.md' to '$TARGET_FILE'."
        exit 0
    else
        echo "Error: Unknown single-argument command '$1'."
        echo "Usage: icmwriper-5-for-ubuntu {d | bo | snb <story-name> | create-html-data-dashboard [-gitee] <project-name> | create-nextjs-web-app [-gitee] <project-name>}"
        exit 1
    fi
fi

# Argument count validation
if [ $# -ne 2 ] && [ $# -ne 3 ]; then
    echo "Usage: icmwriper-5-for-ubuntu {d | bo | snb <story-name> | create-html-data-dashboard [-gitee] <project-name> | create-nextjs-web-app [-gitee] <project-name>}"
    exit 1
fi

# Subcommand routing
if [ "$1" = "snb" ]; then
    # SNB (Story aNd Bubble) subcommand handler
    # Store story name
    STORY_NAME="$2"

    # Check if source story file exists
    if [ ! -f "$STORY_NAME" ]; then
        echo "Error: File '$STORY_NAME' does not exist."
        exit 1
    fi

    # Find bubble template files
    TEMPLATE_FILES=$(find . -maxdepth 1 -name "icm-bubble-template*" | sort)
    if [ -z "$TEMPLATE_FILES" ]; then
        echo "Error: No bubble template files found. Expected files starting with 'icm-bubble-template'."
        exit 1
    fi
    
    # Use the first template file found
    TEMPLATE_FILE=$(echo "$TEMPLATE_FILES" | head -n1)

    # Generate timestamp (will be used for both files)
    TIMESTAMP=$(date +"%Y-%m-%d--%H-%M")

    # Define target filenames
    STORY_TARGET="icm-story-$TIMESTAMP.md"
    BUBBLE_TARGET="icm-bubble-$TIMESTAMP.md"

    # Copy story file
    if ! cp "$STORY_NAME" "$STORY_TARGET"; then
        echo "Error: Failed to copy '$STORY_NAME' to '$STORY_TARGET'."
        exit 1
    fi

    # Copy bubble file
    if ! cp "$TEMPLATE_FILE" "$BUBBLE_TARGET"; then
        echo "Error: Failed to copy '$TEMPLATE_FILE' to '$BUBBLE_TARGET'."
        # Cleanup: remove the story file that was already created
        rm -f "$STORY_TARGET"
        exit 1
    fi

    # Replace the story reference with the newly created story filename
    # Match both numeric timestamps and the template placeholder format
    sed -i "s/@icm-story-\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}--[0-9]\{2\}-[0-9]\{2\}\|yyyy-mm-dd--hh-mm\)\.md/@$STORY_TARGET/g" "$BUBBLE_TARGET"

    # Success message
    echo "Success: Copied '$STORY_NAME' to '$STORY_TARGET'."
    echo "Success: Copied '$TEMPLATE_FILE' to '$BUBBLE_TARGET' and updated story reference to '$STORY_TARGET'."
    exit 0

elif [ "$1" = "create-html-data-dashboard" ]; then
    # Generate HTML Data Dashboard subcommand handler

    # Parse arguments to determine repository source and project name
    if [ $# -eq 3 ] && [ "$2" = "-gitee" ]; then
        # Use Gitee repository
        REPO_URL="https://gitee.com/wubin28/ICMwRIPER-5/raw/main"
        PROJECT_NAME="$3"
        REPO_SOURCE="Gitee"
    elif [ $# -eq 2 ] && [ "$2" != "-gitee" ]; then
        # Use GitHub repository (default)
        REPO_URL="https://raw.githubusercontent.com/wubin28/ICMwRIPER-5/main"
        PROJECT_NAME="$2"
        REPO_SOURCE="GitHub"
    else
        # Invalid arguments
        if [ $# -eq 3 ] && [ "$2" != "-gitee" ]; then
            echo "Error: Invalid flag '$2'. Expected '-gitee'."
        elif [ $# -eq 2 ] && [ "$2" = "-gitee" ]; then
            echo "Error: Missing project name after '-gitee' flag."
        else
            echo "Error: Invalid arguments for create-html-data-dashboard."
        fi
        echo "Usage: icmwriper-5-for-ubuntu create-html-data-dashboard [-gitee] <project-name>"
        exit 1
    fi

    # Directory existence check
    if [ -d "$PROJECT_NAME" ]; then
        echo "Error: Directory '$PROJECT_NAME' already exists."
        exit 1
    fi

    # Define files to download with their paths
    # Root files (5 files)
    ROOT_FILES=("icm-bubble-template.md" "icm-story-template.md" "icmwriper-5.md" "README.md" "icm-bubble-only-template.md")

    # Subdirectory files (2 files)
    SUBDIR_FILES=("for-html-data-dashboard/first-80-rows-agentic_ai_performance_dataset_20250622.xlsx" "for-html-data-dashboard/.gitignore")

    # Create project directory
    if ! mkdir "$PROJECT_NAME"; then
        echo "Error: Failed to create directory '$PROJECT_NAME'."
        exit 1
    fi

    # Download root files
    for filename in "${ROOT_FILES[@]}"; do
        url="$REPO_URL/$filename"
        if ! curl -f -sS -o "$PROJECT_NAME/$filename" "$url"; then
            echo "Error: Failed to download $filename from $REPO_SOURCE. Please check your internet connection and repository availability."
            rm -rf "$PROJECT_NAME"
            exit 1
        fi
    done

    # Download subdirectory files
    for filepath in "${SUBDIR_FILES[@]}"; do
        # Extract just the filename for the target
        filename=$(basename "$filepath")
        url="$REPO_URL/$filepath"
        if ! curl -f -sS -o "$PROJECT_NAME/$filename" "$url"; then
            echo "Error: Failed to download $filepath from $REPO_SOURCE. Please check your internet connection and repository availability."
            rm -rf "$PROJECT_NAME"
            exit 1
        fi
    done

    # Rename README.md
    mv "$PROJECT_NAME/README.md" "$PROJECT_NAME/icmwriper-5-README.md"

    # Success message
    echo "Success: Project '$PROJECT_NAME' created with ICMwRIPER-5 template files and HTML data dashboard resources (7 files downloaded from $REPO_SOURCE)."
    exit 0

elif [ "$1" = "create-nextjs-web-app" ]; then
    # Generate Next.js Web App subcommand handler

    # Parse arguments to determine repository source and project name
    if [ $# -eq 3 ] && [ "$2" = "-gitee" ]; then
        # Use Gitee repository
        REPO_URL="https://gitee.com/wubin28/ICMwRIPER-5/raw/main"
        PROJECT_NAME="$3"
        REPO_SOURCE="Gitee"
    elif [ $# -eq 2 ] && [ "$2" != "-gitee" ]; then
        # Use GitHub repository (default)
        REPO_URL="https://raw.githubusercontent.com/wubin28/ICMwRIPER-5/main"
        PROJECT_NAME="$2"
        REPO_SOURCE="GitHub"
    else
        # Invalid arguments
        if [ $# -eq 3 ] && [ "$2" != "-gitee" ]; then
            echo "Error: Invalid flag '$2'. Expected '-gitee'."
        elif [ $# -eq 2 ] && [ "$2" = "-gitee" ]; then
            echo "Error: Missing project name after '-gitee' flag."
        else
            echo "Error: Invalid arguments for create-nextjs-web-app."
        fi
        echo "Usage: icmwriper-5-for-ubuntu create-nextjs-web-app [-gitee] <project-name>"
        exit 1
    fi

    # Directory existence check
    if [ -d "$PROJECT_NAME" ]; then
        echo "Error: Directory '$PROJECT_NAME' already exists."
        exit 1
    fi

    # Define files to download with their paths
    # Root files (3 files)
    ROOT_FILES=("icmwriper-5.md" "README.md" "icm-bubble-only-template.md")

    # Subdirectory files (3 files)
    SUBDIR_FILES=("for-nextjs-web-app/icm-bubble-template-for-nextjs-web-app.md" "for-nextjs-web-app/icm-story-template-for-nextjs-web-app.md" "for-nextjs-web-app/.gitignore")

    # Create project directory
    if ! mkdir "$PROJECT_NAME"; then
        echo "Error: Failed to create directory '$PROJECT_NAME'."
        exit 1
    fi

    # Download root files
    for filename in "${ROOT_FILES[@]}"; do
        url="$REPO_URL/$filename"
        if ! curl -f -sS -o "$PROJECT_NAME/$filename" "$url"; then
            echo "Error: Failed to download $filename from $REPO_SOURCE. Please check your internet connection and repository availability."
            rm -rf "$PROJECT_NAME"
            exit 1
        fi
    done

    # Download subdirectory files
    for filepath in "${SUBDIR_FILES[@]}"; do
        # Extract just the filename for the target
        filename=$(basename "$filepath")
        url="$REPO_URL/$filepath"
        if ! curl -f -sS -o "$PROJECT_NAME/$filename" "$url"; then
            echo "Error: Failed to download $filepath from $REPO_SOURCE. Please check your internet connection and repository availability."
            rm -rf "$PROJECT_NAME"
            exit 1
        fi
    done

    # Rename README.md
    mv "$PROJECT_NAME/README.md" "$PROJECT_NAME/icmwriper-5-README.md"

    # Success message
    echo "Success: Project '$PROJECT_NAME' created with ICMwRIPER-5 template files and Next.js web app resources (6 files downloaded from $REPO_SOURCE)."
    exit 0
else
    echo "Error: Unknown command '$1'. Supported commands: 'd', 'bo', 'snb', 'create-html-data-dashboard', 'create-nextjs-web-app'."
    exit 1
fi
